class Typewriter {
  constructor(text, callback,speed = 100) {
    this.interval = null;
    this.text = text;
    this.callback = callback;
    this.speed = speed;
    this.index = 0;
		!!text && this.restart();
  }

  setText(val){
    let flag = !!this.text;
    if(typeof val === "function"){
      this.text = val(this.text);
    }else{
      this.text = val;
    }
    if(!flag){
      this.restart();
    }
  }
  restart(){
    const _this = this;
    this.interval && clearInterval(this.interval);
    const interval = setInterval(()=> {
      if (_this.index < _this.text.length) {
        _this.index++;
        _this.callback(_this.text.substring(0, _this.index));
      } else {
        clearInterval(interval);
        this.callback(_this.text);
      }
    }, _this.speed)
    this.interval = interval;
  }

  stop() {
    this.typewriter.stop()
  }
}

module.exports = Typewriter;
